﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using org.swinchester.windowsevents.core;
using System.Diagnostics.Eventing.Reader;
using MongoDB.Driver;

namespace org.swinchester.windowsevents.mongodb
{
    public class MongoWindowsEventEntityDao : MongoDaoBase, IEventRecordProducer
    {
        public void Insert(EventRecord evtRecord)
        {
            //var ent = new WindowsEventEntity { EventRecord = evtRecord };
            var collection = GetCollection();
            MongoWindowsEventEntity wee = ConvertEventRecordToEntity(evtRecord);
            collection.Insert(wee);
        }

        private MongoCollection<MongoWindowsEventEntity> GetCollection()
        {
            return GetMongoDb().GetCollection<MongoWindowsEventEntity>(config.EventEntities);
        }

        private MongoWindowsEventEntity ConvertEventRecordToEntity(EventRecord evtRecord)
        {
            List<string> propertyList = new List<string>();
            foreach (EventProperty ep in evtRecord.Properties)
            {
                propertyList.Add(ep.Value.ToString());
            }

            MongoWindowsEventEntity wee = new MongoWindowsEventEntity
            {
                ActivityId = evtRecord.ActivityId.GetValueOrDefault(),
                WindowsId = evtRecord.Id,
                Keywords = evtRecord.Keywords.GetValueOrDefault().ToString(),
                KeywordsDisplayNames = evtRecord.KeywordsDisplayNames.ToList<string>(),
                Level = evtRecord.Level.GetValueOrDefault().ToString(),
                LevelDisplayName = evtRecord.LevelDisplayName,
                LogName = evtRecord.LogName,
                MachineName = evtRecord.MachineName,
                Opcode = evtRecord.Opcode.GetValueOrDefault(),
                OpcodeDisplayName = evtRecord.OpcodeDisplayName,
                ProcessId = evtRecord.ProcessId.GetValueOrDefault(),
                Properties = propertyList,
                ProviderId = evtRecord.ProviderId.GetValueOrDefault(),
                ProviderName = evtRecord.ProviderName,
                Qualifiers = evtRecord.Qualifiers.GetValueOrDefault(),
                RecordId = evtRecord.RecordId.GetValueOrDefault(),
                RelatedActivityId = evtRecord.RelatedActivityId.GetValueOrDefault(),
                Task = evtRecord.Task.GetValueOrDefault(),
                TaskDisplayName = evtRecord.TaskDisplayName,
                ThreadId = evtRecord.ThreadId.GetValueOrDefault(),
                TimeCreated = evtRecord.TimeCreated.GetValueOrDefault(),
                UserId = evtRecord.UserId.Value,
                Version = evtRecord.Version.GetValueOrDefault().ToString()
            };
            return wee;

        }
    }
}
